package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.system.controller.dto.UpShopTask;
import cn.stylefeng.guns.modular.system.entity.Store;
import cn.stylefeng.guns.modular.system.entity.UpShop;
import cn.stylefeng.guns.modular.system.entity.UpShopAudit;
import cn.stylefeng.guns.modular.system.entity.ZApplication;
import cn.stylefeng.guns.modular.system.mapper.StoreMapper;
import cn.stylefeng.guns.modular.system.mapper.UpShopMapper;
import cn.stylefeng.guns.modular.system.model.params.IndentOrderAuditParam;
import cn.stylefeng.guns.modular.system.model.params.StoreParam;
import cn.stylefeng.guns.modular.system.model.params.UpShopAuditParam;
import cn.stylefeng.guns.modular.system.model.params.UpShopParam;
import cn.stylefeng.guns.modular.system.model.result.StoreResult;
import cn.stylefeng.guns.modular.system.service.StoreService;
import cn.stylefeng.guns.modular.system.service.UpShopAuditService;
import cn.stylefeng.guns.modular.system.service.UpShopService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.util.common.ResponseMsg;
import cn.stylefeng.guns.sys.core.util.common.SystemConstant;
import cn.stylefeng.guns.sys.core.util.common.UploadFileUtils;
import cn.stylefeng.guns.sys.core.util.common.UploadResult;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.jsonwebtoken.impl.crypto.MacProvider;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.bpmn.behavior.ServiceTaskJavaDelegateActivityBehavior;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 门店表控制器
 * 新增门店
 * @author 小飞
 * @Date 2019-07-11 03:14:13
 */
@Controller
@RequestMapping("/store")
public class StoreController extends BaseController {


    private String PREFIX = "/store";

    //申请门店Service层
    @Autowired
    private StoreService storeService;
    //申请人Service层
    @Autowired
    private UpShopService upShopService;
    @Autowired
    private UpShopMapper upShopMapper;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private UpShopAuditService upShopAuditService;
    @Autowired
    private StoreMapper storeMapper;



    /**
     * 跳转到主页面
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/store.html";
    }


    /**
     * 跳转到开店申请拓展部审批页面
     */
    @RequestMapping("/indexCheck")
    public String indexCheck() {
        return PREFIX + "/storeCheck.html";
    }


    /**
     * 新增页面
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/add")
    public String add(Model model) {
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        return PREFIX + "/store_add.html";
    }


    /**
     * 编辑页面
     * 进入开店详情页面
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/edit")
    public String edit(Model model, Long id, String taskId, HttpSession session) {
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        model.addAttribute("ids",id);
        model.addAttribute("taskId",taskId);
        session.setAttribute("z_application_id",id);
        return PREFIX + "/store_edit.html";
    }


    /**
     * 新增接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(StoreParam storeParam,UpShopParam upShopParam) {
        String Longtitude = storeParam.getStoreLongtitude().substring(0, 10);
        String Latitude = storeParam.getStoreLongtitude().substring(11, 18);

        //存入数据库经度
        storeParam.setStoreLongtitude(Longtitude);
        //存入数据库纬度
        storeParam.setStorelatitude(Latitude);
        //存入门店图片
        storeParam.setPicPath(SystemConstant.TENCENT_URL+storeParam.getPicPath());
        //存入门店附件
        storeParam.setAccessoryPath(SystemConstant.TENCENT_URL+storeParam.getAccessoryPath());
        this.storeService.add(storeParam);

        //新增申请人表数据
        Long storeId = this.storeService.QueryStoreMax();
        UpShop upShop = new UpShop();
        upShop.setTime(new Date());
        upShop.setStoreId(storeId);
        upShop.setCheckCode(1);
        //存入申请人id
        upShop.setUserId(ShiroKit.getUserNotNull().getId());
        //存入登录帐号
        upShop.setLoginNum(ShiroKit.getUserNotNull().getAccount());
        //存入设计图纸
        //upShop.setPaperPath(SystemConstant.TENCENT_URL+upShopParam.getPaperPath());
        //存入备注
        upShop.setRemark(upShopParam.getRemark());
        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId()+  "");
        ProcessInstance processInstance =  runtimeService.startProcessInstanceByKey(SystemConstant.openShop);
        upShop.setProcessInstanceId(processInstance.getId());

        BigDecimal upstatus= new BigDecimal(0);
        Long upstatuss= upstatus.longValue();
        upShop.setUpStatus(upstatuss);
        upShopMapper.insert(upShop);

        //开启流程
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),ShiroKit.getUserNotNull().getId() + "");
        taskService.complete(task.getId());
        return ResponseData.success();
    }


    /**
     * 编辑接口
     * 修改接口
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(StoreParam storeParam,UpShopParam upShopParam) {
        String Longtitude = storeParam.getStoreLongtitude().substring(0, 10);
        String Latitude = storeParam.getStoreLongtitude().substring(11, 18);
        storeParam.setStoreName(storeParam.getStoreName());
        storeParam.setAddressDetail(storeParam.getAddressDetail());
        storeParam.setCash(storeParam.getCash());
        storeParam.setAcountNum(storeParam.getAcountNum());
        //存入数据库经度
        storeParam.setStoreLongtitude(Longtitude);
        //存入数据库纬度
        storeParam.setStorelatitude(Latitude);
        //存入门店图片
        storeParam.setPicPath(SystemConstant.TENCENT_URL+storeParam.getPicPath());
        //存入门店附件
        storeParam.setAccessoryPath(SystemConstant.TENCENT_URL+storeParam.getAccessoryPath());
        storeParam.setStoreId(storeParam.getStoreId());
        this.storeService.UpdateStoreId(storeParam);

        UpShopParam upShop = new UpShopParam();
        //修改申请人表
        upShop.setRemark(upShopParam.getRemark());
        //upShop.setPaperPath(SystemConstant.TENCENT_URL+upShopParam.getPaperPath());
        upShop.setStoreId(storeParam.getStoreId());
        upShopMapper.UpdateUpShop(upShop);
        return ResponseData.success();
    }


    /**
     * 删除接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(StoreParam storeParam) {
        this.storeService.delete(storeParam);
        upShopMapper.DeleteStoreId(storeParam.getId());
        return ResponseData.success();
    }


    /**
     * 查看详情接口
     *
     * @author 小飞
     * @Date 2019-07-11
     */
    @RequestMapping("/detail")
    @ResponseBody
    public LayuiPageInfo detail(HttpSession session) {
        LayuiPageInfo lyp = new LayuiPageInfo();
        Object id = session.getAttribute("z_application_id");
        long l = Long.valueOf(String.valueOf(id));
        List<StoreResult> detail = storeService.QueryTwoId(l);
        lyp.setData(detail);
        return lyp;
    }


    /**
     * 查询所有的门店和申请人
     * @author 小飞
     * @Date 2019-07-11
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo QueryStoreAll(String condition) {
        LayuiPageInfo lyf = new LayuiPageInfo();
        List<Store> list = storeService.QueryStoreAll(condition);
        lyf.setData(list);
        return lyf;
    }


    /**
     * 获取开店申请审核记录
     * @return
     */
    @ResponseBody
    @RequestMapping("/getUpShopListCheck")
    public LayuiPageInfo getUpShopListCheck(){

          List<Task> tasks = taskService.createTaskQuery().processDefinitionKey(SystemConstant.openShop).taskCandidateUser(ShiroKit.getUserNotNull().getId() +"").list();
          if (tasks.size() == 0){
              return  new LayuiPageInfo();
          }
        List<UpShopTask> upShopTasks = tasks.stream().filter(task -> upShopService.getByProcessInstanceId(task.getProcessInstanceId())!= null).map(task -> {
            UpShopTask upShopTask = new UpShopTask();
            UpShop  upShop = upShopService.getByProcessInstanceId(task.getProcessInstanceId());
            BeanUtils.copyProperties(upShop,upShopTask);
            upShopTask.setUserName(userService.getById(upShop.getUserId()).getName());
            upShopTask.setDeptName(deptService.getById(userService.getById(upShop.getUserId()).getDeptId()).getSimpleName());
            upShopTask.setProcessInstanceId(task.getProcessInstanceId());
            upShopTask.setTaskId(task.getId());
            upShopTask.setRemarks(upShop.getRemark());
            return  upShopTask;
        }).collect(Collectors.toList());

        LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
        layuiPageInfo.setCount(upShopTasks.size());
        layuiPageInfo.setData(upShopTasks);
        return  layuiPageInfo;
    }


    /**
     * 审核
     */
        @ResponseBody
        @RequestMapping("/check")
        public ResponseData check(UpShopAuditParam upShopAuditParam, HttpSession session, UpShopParam upShopParam){
            UpShopAudit upShopAudit = new UpShopAudit();
            BeanUtils.copyProperties(upShopAuditParam,upShopAudit);
            upShopAudit.setAuditTime(new Date());
            Task task = taskService.createTaskQuery().taskId(upShopAuditParam.getTaskId()).singleResult();
            upShopAudit.setTaskId(task.getId());
            upShopAudit.setProcessInstanceId(task.getProcessInstanceId());
            upShopAudit.setUserId(ShiroKit.getUserNotNull().getId());
            //取出门店id存入
            Object StoreID = session.getAttribute("StoreID");
            long ids = Long.valueOf(String.valueOf(StoreID));
            upShopAudit.setUpShopId(ids);
            upShopAudit.setComment(upShopAuditParam.getComment());
            upShopAuditService.save(upShopAudit);

            //修改审核状态
            upShopParam.setCheckCode(1);
            Long status = new Long((long)1);
            upShopParam.setUpStatus(status);
            upShopParam.setId(upShopParam.getId());
            upShopService.update(upShopParam);

            UpShop upShop = upShopService.getById(upShopAuditParam.getId());
            if (ShiroKit.hasRole("设计部审核人员")){
               upShop.setPaperPath(upShopAuditParam.getPaperPath());
            }else if (ShiroKit.hasRole("销售部服务部审核人员")){
                upShop.setPaperPath(upShopAuditParam.getLoginNum());
            }else if(ShiroKit.hasRole("区域经理")){
                upShop.setPaperPath(upShopAuditParam.getLoginNum());
            }

            upShopService.getBaseMapper().updateById(upShop);

            //完成流程
            Map<String,Object> map = new HashMap<>();
            map.put("status",upShopAuditParam.getAuditStatus());
            taskService.complete(task.getId(),map);
           return  ResponseData.success();
        }


    /**
     *上传文件接口
     */
    @RequestMapping("/uploadFile")
    public ResponseEntity<?> uploadFile(MultipartFile multipartFile){
        ResponseMsg msg = new ResponseMsg();
        msg = UploadFileUtils.uploadFile(multipartFile);
        if (msg.getStatus() == 10001){
            UploadResult uploadResult = (UploadResult) msg.getResult();
            msg.setStatus(10001);
            msg.setDesc("上传成功");
            msg.setResult(SystemConstant.TENCENT_URL + uploadResult.getPath());
            return  new ResponseEntity<>(msg, HttpStatus.OK);
        }else {
            msg.setDesc("上传失败");
            msg.setStatus(10002);
            return  new ResponseEntity<>(msg,HttpStatus.OK);
        }
    }


    //上传图片
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public ResponseData uploadUtils(@RequestPart("file") MultipartFile file) throws FileNotFoundException {

      if (ToolUtil.isEmpty(file)){
          return  ResponseData.error(201,"上传失败，图片为空");
      }else{

          ResponseMsg msg = UploadFileUtils.uploadFile(file);

          if (msg.getStatus() == 10001){
              UploadResult result = (UploadResult) msg.getResult();
              return  ResponseData.success(200,"上传成功",result.getPath());
          }else {
              return  ResponseData.error(202,"上传失败，图片格式错误");
          }

      }

    }


    /**
     * 查询所有门店的经纬度
     */
    @RequestMapping(value = "/queryStoreJW", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData queryStoreJW() {
        return ResponseData.success(storeService.QueryStoreAll(null));
    }

    /**
     * 区域经理进入详情页面
     */
    @RequestMapping("/RegionalManagerEdit")
    public String RegionalManagerEdit(Model model, Long id, String taskId, HttpSession session) {
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        model.addAttribute("ids",id);
        model.addAttribute("taskId",taskId);
        session.setAttribute("RegionalManager_id",id);
        return PREFIX + "/RegionalManager_edit.html";
    }

    /**
     * 区域经理根据id查询详情返回的页面
     */
    @ResponseBody
    @RequestMapping("/QueryRegionalManagerdetail")
    public LayuiPageInfo QueryRegionalManagerdetail(HttpSession session) {
        LayuiPageInfo lyp = new LayuiPageInfo();
        Object id = session.getAttribute("RegionalManager_id");
        long ids = Long.valueOf(String.valueOf(id));
        List<StoreResult> detail = storeService.QueryUpShopId(ids);
        for(int i = 0; i<detail.size(); i++){
             //存入门店id
            session.setAttribute("StoreID",detail.get(i).getId());
        }
        lyp.setData(detail);
        return lyp;
    }


    /**
     * 跳转到区域经理审核页面
     */
    @RequestMapping("/RegionalManager_shenghe")
    public String RegionalManager_shenghe(String id,String taskId,Model model) {
        model.addAttribute("id",id);
        model.addAttribute("taskId",taskId);
        return PREFIX + "/store_shenghe.html";
    }


    /**
     * 查询审核过后的数据
     */
    @ResponseBody
    @RequestMapping("/QueryAuditInformation")
    public LayuiPageInfo QueryAuditInformation() {
        LayuiPageInfo lyp = new LayuiPageInfo();
        lyp.setData(upShopAuditService.list());
        return lyp;
    }


































}


